from decorators import token_required_with_response, response_json
from sanic import Blueprint
from controllers.user import UserController
from utils.parser import parse_args


bp = Blueprint("user", url_prefix="/user")


@bp.route("/register", methods=["POST"])
@response_json
async def register(request):
    """
    注册用户
    """
    args_rules = [
        dict(arg="email", required=False, type="str", default="", help="邮箱"),
        dict(arg="username", required=True, type="str", help="用户名"),
        dict(arg="password", required=True, type="str", help="密码"),
        dict(arg="register_code", required=True, type="str", help="邀请码"),
    ]
    args = parse_args(request, "json", args_rules)
    user = UserController.register(**args)
    return {
        "id": user["id"],
        "email": user["email"],
        "username": user["username"],
        "available": user["available"],
    }


@bp.route("/login", methods=["POST", "OPTIONS"])
@response_json
async def login(request):
    """
    登录， 邮箱或用户名方式
    """
    args_rules = [
        dict(arg="username", required=True, type="str", help="用户名"),
        dict(arg="password", required=True, type="str", help="密码")
    ]
    args = parse_args(request, "json", args_rules)
    token = UserController.login(**args)

    return {"token": token}


@bp.route("/thirdLogin", methods=["POST"])
@response_json
async def third_login(request):
    args_rules = [
        dict(arg="code", required=True, type="str", help="code"),
        dict(arg="project", required=True, type="str", help="来自哪个项目"),
    ]
    args = parse_args(request, "json", args_rules)
    token = UserController.third_login(**args)

    return {"token": token}


@bp.route("/editpassword", methods=["POST"])
@token_required_with_response
async def edit_password(request, user):
    args_rules = [
        dict(arg="password", required=True, type="str", help="密码"),
    ]
    args = parse_args(request, "json", args_rules)
    UserController(id=user["id"]).edit_password(**args)

    return {}


@bp.route("/retrievepassword", methods=["POST"])
@response_json
async def retrieve_password(request):
    """
    找回密码
    """
    args_rules = [
        dict(arg="email", required=True, type="str", help="邮箱"),
        dict(arg="username", required=True, type="str", help="用户名"),
    ]
    args = parse_args(request, "json", args_rules)
    UserController.retrieve_password(**args)
    return {}


@bp.route("/resetpassword", methods=["POST"])
@response_json
async def reset_password(request):
    """
    重设密码
    """
    args_rules = [
        dict(arg="token", required=True, type="str", help="token标识"),
        dict(arg="password", required=True, type="str", help="密码")
    ]
    args = parse_args(request, "json", args_rules)
    UserController.reset_password(**args)
    return {}

